import { ref, Ref, computed, ComputedRef } from 'vue'
import Project from '../types/Project';
import { BudgetViewModel } from '../types/Budget';
import dayjs from 'dayjs';
import app from '@/app';

/**
 * 生成用以申请表的视图模型
 * @param proj 缓存的项目
 * @returns 
 */
export function useBudget(proj: Project) {
    //读取缓存得到上一次保存的结果进行重置
    function reset() {
        let init : BudgetViewModel[] = proj.toBudgetViewModel();
        budgets.value=[...init];
    }
    const budgets: Ref<BudgetViewModel[]> = ref([]);
    const errorStrings: Ref<string[]> = ref([]);
    const total: ComputedRef<number> = computed(() => budgets.value.reduce((acc, cur) => acc + (cur.budgetAmount > 0 ? cur.budgetAmount : 0), 0));
    const approvalAmount = proj.basicInfo.ApprovalAmount;
    const overBudget: ComputedRef<boolean> = computed(() => total.value !== approvalAmount && approvalAmount > 0);
    reset();

    //校验
    async function validate(): Promise<boolean> {
        errorStrings.value = [];
        const projStartDate = proj.basicInfo.ApplyStartDate;
        const projEndDate = proj.basicInfo.ApplyEndDate;

        if(total.value != approvalAmount && approvalAmount > 0){
            errorStrings.value.push(`预算必须等于${approvalAmount}元（学校批准预算）`);
            return false;
        }

        for (let budget of budgets.value) {
            if (budget.useTime === '' || budget.useTime === app.DATE_EMPTY) {
                continue;
            };
            if (projStartDate && dayjs(budget.useTime).isBefore(dayjs(projStartDate))) {
                errorStrings.value.push(`${budget.budgetName}：预算使用时间不能早于项目申请时间 ${projStartDate}`);
                return false;
            }
            if (projEndDate && dayjs(budget.useTime).isAfter(dayjs(projEndDate))) {
                errorStrings.value.push(`${budget.budgetName}：预算使用时间不能晚于项目结束时间 ${projEndDate}`);
                return false;
            }
        }

        return true;
    }
    
    return {
        budgets,
        total,
        approvalAmount,
        overBudget,
        errorStrings,
        validate,
        reset,
    }
}

export default useBudget;